package com.hzj.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzj.pojo.VoteUser;
import com.hzj.service.VoteUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hzj
 * @since 2021-03-19
 */
@Controller

public class VoteUserController {
    @Autowired
    VoteUserService vus;

    @RequestMapping("/unauthorized")
    @ResponseBody
    public String unauthorized(Model model) {
//        System.out.println("无权限");
//        model.addAttribute("error", "无权限，请先登录管理员账号");
        return "你不是管理员，无法操作此页面";
    }

    @RequestMapping("/login")
    public String login(String vuUserName, String vuPassword, Model model, HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(vuUserName, vuPassword);
        try {
            // 执行登录操作，shiro帮你验证，如果有错误就会报异常

//            System.out.println(subject.isRemembered());
//            //是否记住用户
//            System.out.println("boolen======>" + rememberMe);
//            token.setRememberMe(rememberMe);
            ServletContext application = session.getServletContext();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("vu_User_Name", vuUserName);
            VoteUser user = vus.getOne(queryWrapper);
            Object obj = application.getAttribute(vuUserName);
            if (obj != null) {
                //已登录
                model.addAttribute("error", "已登录，请先退出再登录");
                return "login";
            } else if (user != null) {
                application.setAttribute(vuUserName, vuUserName);
            }
            subject.login(token);
//是否记住用户
// token.setRememberMe(true);

//成功就会返回到指定页面
            session.setAttribute("userId", user.getVuUserId());
            session.setMaxInactiveInterval(86400);
            return "redirect:/showList";
        } catch (UnknownAccountException e) {
            model.addAttribute("error", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("error", "密码不存在");
            return "login";
        } catch (LockedAccountException lae) {
            model.addAttribute("error", "用户被锁定，不能登录");
            return "login";
        } catch (AuthenticationException ae) {
            model.addAttribute("error", "严重的错误");
            return "login";
        }
    }

    @RequestMapping("/")
    public String tologin() {
        Subject subject = SecurityUtils.getSubject();
//        System.out.println("是否被记住==========>：" + subject.isRemembered() + "|" + subject.isAuthenticated());
        if (subject.isAuthenticated()) {
            return "forward:/showList";
        }
        return "login";
    }

    @GetMapping("/logOut")
    public String logOut(HttpSession session, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        VoteUser user = (VoteUser) subject.getPrincipal();
        subject.logout();
        if (request.getSession(false) != null)
            session.removeAttribute("userId");
        ServletContext application = session.getServletContext();
        application.removeAttribute(user.getVuUserName());
        return "login";
    }

    @PostMapping("/addUser")
    public String addUser(VoteUser user, Model model) {
        if (user == null || user.getVuUserName().equals("") || user.getVuPassword().equals("")) {
            model.addAttribute("point", "请将内容填写完整");
        }
        user.setVuStatus(1);
        boolean save = vus.save(user);
        if (save) {
            return "login";
        } else {
            return "redirect:regist.html";
        }
    }

    @GetMapping("/findUser")
    @ResponseBody
    public int findUser(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("vu_User_Name", name);
        VoteUser user = vus.getOne(queryWrapper);
        if (user == null) {
            return 1;
        }
        return 0;
    }

}

